<template>
  <div>
    <!-- 添加和修改章节表单 -->
    <el-dialog :visible="dialogFormVisible" :title="title" @close="close()">
      <el-form :model="chapter" >
        <el-form-item label-width="formLableWidth" label="章节标题">
          <el-input v-model="chapter.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label-width="formLableWidth" label="章节排序">
          <el-input-number v-model="chapter.sort" :min="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button :disabled="flag" type="primary" @click="saveOrUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import courseApi from '@/api/course'
export default {

  data() {
    return {
      title: '新增章节',
      flag: false,
      dialogFormVisible: false,
      chapter: {
        sort: 0
      },
      formLableWidth: '80px'
    }
  },

  methods: {
    getChapter(chapterId) {
      // 查询要更新的chapter数据回显
      this.title = '更新章节'
      courseApi.getChapter(chapterId).then(response => {
        this.chapter = response.data.item
        this.open()
      })
    },
    open() {
      // 打开对话框
      this.dialogFormVisible = true
    },

    close() {
      // 关闭对话框
      this.dialogFormVisible = false
      this.$parent.getChapterNestedList()
      // 设置提交按钮可用，重置表单
      this.flag = false
      this.resetForm()
    },
    resetForm() {
      this.chapter = {
        sort: 0
      }
    },

    saveOrUpdate() {
      if (!this.chapter.id) {
        this.save()
      } else {
        this.update()
      }
    },

    save() {
      this.flag = true
      // 将章节绑定到课程中
      this.chapter.courseId = this.$parent.$parent.courseId
      courseApi.saveChapter(this.chapter).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        // this.$parent.getChapterNestedList()
        // 设置提交按钮可用，重置表单
        // this.flag = false
      })
    },
    update() {
      courseApi.updateChapter(this.chapter).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        // this.$parent.getChapterNestedList()
        // this.flag = false
      })
    }
  }
}
</script>
